package com.bstek.urule.console.servlet.client;

import com.bstek.urule.RuleException;
import com.bstek.urule.Utils;
import com.bstek.urule.console.repository.ClientConfig;
import com.bstek.urule.console.servlet.base.BaseController;
import com.bstek.urule.console.EnvironmentUtils;
import com.bstek.urule.console.User;
import com.bstek.urule.console.repository.RepositoryService;
import com.bstek.urule.console.repository.RepositoryServiceImpl;
import com.bstek.urule.console.servlet.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zhouchaoliang
 * @since 2021/12/8
 */
@Controller
public class ClientConfigController extends BaseController {
    @Autowired
    private RepositoryService repositoryService;


    @GetMapping("/urule/clientconfig")
    public ModelAndView client(HttpServletRequest req) {
        ModelAndView mv = new ModelAndView("/client-config-editor");
        mv.addObject("contextPath", req.getContextPath());
        return mv;
    }

    @ResponseBody
    @PostMapping(value = "/urule/clientconfig/loadData")
    public List<ClientConfig> loadData(@RequestParam("project") String project, HttpServletResponse resp) throws Exception {
        project= Utils.decodeURL(project);
        return repositoryService.loadClientConfigs(project);
    }

    @ResponseBody
    @PostMapping(value = "/urule/clientconfig/save")
    public void save(@RequestParam("project") String project, HttpServletRequest req, HttpServletResponse resp) {
        project=Utils.decodeURL(project);
        String file=project+"/"+ RepositoryServiceImpl.CLIENT_CONFIG_FILE;
        String content=req.getParameter("content");
        content=Utils.decodeURL(content);
        User user= EnvironmentUtils.getLoginUser(new RequestContext(req, resp));
        try{
            repositoryService.saveFile(file, content, false,null,user);
        }catch(Exception ex){
            throw new RuleException(ex);
        }
    }
}
